#include "basic.h"
#include <cstdlib>

void extract_patch(const image_data &img, int x, int y, int rf_size, real_num *p)
{
	assert(x >=0 && x+rf_size-1 < img.height);
	assert(y >=0 && y+rf_size-1 < img.width);
	for (int c = 0; c < img.channels; ++c)
		for (int i = 0; i < rf_size; ++i)
			for (int j = 0; j < rf_size; ++j) {
				real_num val = img.a[c][x+i][y+j];
				p[c*rf_size*rf_size + i*rf_size + j] = val;
			}
}

void normalize_patch(real_num *p, int patch_size)
{
	// subtract the mean
	real_num mean = 0.;
	for (int i = 0; i < patch_size; ++i)
		mean += p[i];
	mean /= (real_num)patch_size;
	for (int i = 0; i < patch_size; ++i)
		p[i] -= mean;
	// divide by the standard deviation	
	real_num sd = 0.;
	for (int i = 0; i < patch_size; ++i)
		sd += sqr(p[i]);
	sd /= (real_num)(patch_size - 1);
	sd = sqrt(sd + 10);
	for (int i = 0; i < patch_size; ++i)
		p[i] /= sd;
}

/*
void matrix_mult(const MatrixR &a, const MatrixR &b, MatrixR &c)
{
	MatrixF x = a.cast<float>();
	MatrixF y = b.cast<float>();
	c.noalias() = (x * y).cast<real_num>();
}
*/
